package com.zhoug.widget.dialog.date;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.NumberPicker;
import android.widget.TextView;


import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.TimeUtils;
import com.zhoug.widget.R;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;

/**
 * 日期选择器 年月日
 */
public class DateChooser extends Dialog implements IDateChooser, View.OnClickListener, NumberPicker.OnValueChangeListener {
    private static final String TAG = "DateChooser";
    private String mTitle = "选择日期";
    private String mYear;
    private String mMonth;
    private String mDay;
    private String mHour;
    private String mMinute;

    private String mMaxYear;//最大年
    private String mMaxMonth;//最大月
    private String mMaxDay;//最大日


    private Callback mCallback;
    private Object mTag;

    private NumberPicker mNumberPickerYear;//年
    private NumberPicker mNumberPickerMonth;//月
    private NumberPicker mNumberPickerDay;//日
    private NumberPicker mNumberPickerHour;//时
    private NumberPicker mNumberPickerMinute;//分
    private ViewGroup mContainerDate;
    private ViewGroup mContainerTime;

    private TextView mTvTitle;
    private TextView mTvCancel;
    private TextView mTvOk;

    private int flag = FLAG_DATE;

    private ArrayList<String> dayList;//天数


    public DateChooser(@NonNull Context context) {
        this(context, R.style.widgets_dialog_full);

    }

    public DateChooser(@NonNull Context context, int themeResId) {
        super(context, themeResId);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//必须设置无标题 否则不会匹配内容
        setContentView(R.layout.widgets_dialog_date);
        init();
        initView();
        initDate();
    }

    private void init() {
        try {
            String[] split = TimeUtils.getCurrentTime("yyyy-MM-dd-HH-mm").split("-");
            if (mYear == null) {
                if (mMaxYear != null && TimeUtils.compareInt(split[0], mMaxYear) > 0) {
                    mYear = mMaxYear;
                } else {
                    mYear = split[0];
                }
            }
            if (mMonth == null) {
                if (mMaxMonth != null && TimeUtils.compareInt(split[1], mMaxMonth) > 0) {
                    mMonth = mMaxMonth;
                } else {
                    mMonth = split[1];
                }
            }
            if (mDay == null) {
                if (mMaxDay != null && TimeUtils.compareInt(split[2], mMaxDay) > 0) {
                    mDay = mMaxDay;
                } else {
                    mDay = split[2];
                }
            }
            if (mHour == null) {
                mHour = split[3];
            }
            if (mMinute == null) {
                mMinute = split[4];
            }
            LogUtils.d(TAG, "init date:" + mYear + "-" + mMonth + "-" + mDay + " " + mHour + ":" + mMinute);
            LogUtils.d(TAG, "init maxDate:" + mMaxYear + "-" + mMaxMonth + "-" + mMaxDay);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        setWindowAnimations(R.style.common_anim_window_popu_down);
        mNumberPickerYear = findViewById(R.id.date_numberPicker_year);
        mNumberPickerMonth = findViewById(R.id.date_numberPicker_month);
        mNumberPickerDay = findViewById(R.id.date_numberPicker_day);
        mNumberPickerHour = findViewById(R.id.date_numberPicker_hour);
        mNumberPickerMinute = findViewById(R.id.date_numberPicker_minute);


        mTvTitle = findViewById(R.id.date_title);
        mTvCancel = findViewById(R.id.date_cancel);
        mTvOk = findViewById(R.id.date_ok);
        mContainerDate = findViewById(R.id.container_date);
        mContainerTime = findViewById(R.id.container_time);
        //选择日期
        if (flag == FLAG_DATE) {
            mContainerDate.setVisibility(View.VISIBLE);
            mContainerTime.setVisibility(View.GONE);
        } else if (flag == FLAG_TIME) {
            //选择时间
            mContainerDate.setVisibility(View.GONE);
            mContainerTime.setVisibility(View.VISIBLE);
        } else {
            //选择日期和时间
            mContainerDate.setVisibility(View.VISIBLE);
            mContainerTime.setVisibility(View.VISIBLE);
        }

        mTvCancel.setOnClickListener(this);
        mTvOk.setOnClickListener(this);
        mNumberPickerYear.setOnValueChangedListener(this);
        mNumberPickerMonth.setOnValueChangedListener(this);

    }

    private void initDate() {
        mTvTitle.setText(mTitle);
        //初始化年
        ArrayList<String> yearList = null;
        if (mMaxYear == null) {
            yearList = TimeUtils.getYearList("2150");
        } else {
            yearList = TimeUtils.getYearList(mMaxYear);
        }
        String[] years = new String[yearList.size()];
        yearList.toArray(years);
        mNumberPickerYear.setMinValue(0);
        mNumberPickerYear.setMaxValue(years.length - 1);
        mNumberPickerYear.setDisplayedValues(years);
        setSelectedYear(mYear);

        //初始化月
        initMonth(mYear);
        mNumberPickerMonth.setMinValue(0);
        setSelectedMonth(mMonth);
        //初始化日
        initDay(mYear, mMonth);
        mNumberPickerDay.setMinValue(0);
        setSelectedDay(mDay);

        //初始化时
        ArrayList<String> hourList = TimeUtils.getHourList();
        String[] hours = new String[hourList.size()];
        hourList.toArray(hours);
        mNumberPickerHour.setMinValue(0);
        mNumberPickerHour.setMaxValue(hours.length - 1);
        mNumberPickerHour.setDisplayedValues(hours);
        setSelectedHour(mHour);
        //初始化分
        ArrayList<String> minuteList = TimeUtils.getMinuteList();
        String[] minutes = new String[minuteList.size()];
        minuteList.toArray(minutes);
        mNumberPickerMinute.setMinValue(0);
        mNumberPickerMinute.setMaxValue(minutes.length - 1);
        mNumberPickerMinute.setDisplayedValues(minutes);
        setSelectedMinute(mMinute);

    }

    /**
     * 初始化月
     *
     * @param year
     */
    private void initMonth(String year) {
        ArrayList<String> monthList = null;
        String[] displayedValues = mNumberPickerMonth.getDisplayedValues();
        if (displayedValues == null) {
            if (mMaxMonth != null && !"12".equals(mMaxMonth) && year.equals(mMaxYear)) {
                monthList = TimeUtils.getMonthList(mMaxMonth);
                LogUtils.d(TAG, "initMonth1:" + monthList.size());
            } else {
                monthList = TimeUtils.getMonthList("12");
                LogUtils.d(TAG, "initMonth2:" + monthList.size());
            }
        } else {
            //设置了最大月
            if (mMaxMonth != null && !"12".equals(mMaxMonth)) {
                //切换到了最大月
                if (displayedValues.length == 12 && year.equals(mMaxYear)) {
                    monthList = TimeUtils.getMonthList(mMaxMonth);
                    LogUtils.d(TAG, "initMonth:切换到了最大月:" + monthList.size());
                } else if (displayedValues.length != 12 && !year.equals(mMaxYear)) {
                    //最大月切出
                    monthList = TimeUtils.getMonthList("12");
                    LogUtils.d(TAG, "initMonth:最大月切出:" + monthList.size());

                }
            }
        }
        if (monthList != null) {
            String[] months = new String[monthList.size()];
            monthList.toArray(months);
            mNumberPickerMonth.setDisplayedValues(null);
            mNumberPickerMonth.setMaxValue(months.length - 1);
            mNumberPickerMonth.setDisplayedValues(months);
        }


    }

    /**
     * 初始化日
     *
     * @param year
     * @param month
     */
    private void initDay(String year, String month) {
        if (dayList == null) {
            dayList = new ArrayList<>();
        }
        dayList.clear();
        TimeUtils.getDays(year, month, dayList);
        //最大日期
        if (year.equals(mMaxYear) && month.equals(mMaxMonth)) {
            if (mMaxDay != null) {
                try {
                    int endDay = Integer.parseInt(mMaxDay);
                    //移除最大值以后的日期
                    if (dayList.size() > endDay) {
                        for (int i = dayList.size() - 1; i > endDay - 1; i--) {
                            dayList.remove(i);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        String[] days = new String[dayList.size()];
        dayList.toArray(days);
//        Log.i(TAG, "initDay: ");
        mNumberPickerDay.setDisplayedValues(null);//解决ArrayIndexOutOfBoundsException
        mNumberPickerDay.setMaxValue(days.length - 1);
        mNumberPickerDay.setDisplayedValues(days);

    }


    /**
     * 设置选择的年
     *
     * @param year
     */
    private void setSelectedYear(String year) {
        String[] years = mNumberPickerYear.getDisplayedValues();
        for (int i = 0; i < years.length; i++) {
            if (years[i].equals(year)) {
                mNumberPickerYear.setValue(i);
                break;
            }
        }
    }

    /**
     * 设置选择的月
     *
     * @param month
     */
    private void setSelectedMonth(String month) {
        String[] months = mNumberPickerMonth.getDisplayedValues();
        for (int i = 0; i < months.length; i++) {
            if (months[i].equals(month)) {
                mNumberPickerMonth.setValue(i);
                break;
            }
        }
    }

    /**
     * 设置选择的日
     *
     * @param day
     */
    private void setSelectedDay(String day) {
        String[] days = mNumberPickerDay.getDisplayedValues();
        for (int i = 0; i < days.length; i++) {
            if (days[i].equals(day)) {
                mNumberPickerDay.setValue(i);
                break;
            }
        }
    }

    /**
     * 设置选择的时
     *
     * @param hour
     */
    private void setSelectedHour(String hour) {
        String[] hours = mNumberPickerHour.getDisplayedValues();
        for (int i = 0; i < hours.length; i++) {
            if (hours[i].equals(hour)) {
                mNumberPickerHour.setValue(i);
                break;
            }
        }
    }

    /**
     * 设置选择的分
     *
     * @param minute
     */
    private void setSelectedMinute(String minute) {
        String[] minutes = mNumberPickerMinute.getDisplayedValues();
        for (int i = 0; i < minutes.length; i++) {
            if (minutes[i].equals(minute)) {
                mNumberPickerMinute.setValue(i);
                break;
            }
        }
    }


    @Override
    public IDateChooser setTitle(String title) {
        this.mTitle = title;
        return this;
    }

    @Override
    public IDateChooser setYear(String year) {
        this.mYear = year;
        return this;
    }

    @Override
    public IDateChooser setMonth(String month) {
        this.mMonth = TimeUtils.addZero(month);
        return this;
    }

    @Override
    public IDateChooser setDay(String day) {
        this.mDay = TimeUtils.addZero(day);
        return this;
    }

    @Override
    public IDateChooser setMaxYear(String maxYear) {
        this.mMaxYear = maxYear;
        return this;
    }

    @Override
    public IDateChooser setMaxMonth(String maxMonth) {
        this.mMaxMonth = TimeUtils.addZero(maxMonth);
        return this;
    }

    @Override
    public IDateChooser setMaxDay(String maxDay) {
        this.mMaxDay = TimeUtils.addZero(maxDay);
        return this;
    }

    @Override
    public IDateChooser setMax(String maxYear, String maxMonth, String maxDay) {
        this.mMaxYear = maxYear;
        this.mMaxMonth = TimeUtils.addZero(maxMonth);
        this.mMaxDay = TimeUtils.addZero(maxDay);
        return this;
    }

    @Override
    public IDateChooser setMax(String date) {
        if(date!=null){
            String[] split = date.split("-");
            this.mMaxYear = split[0];
            this.mMaxMonth = split[1];
            this.mMaxDay =  split[2];

        }else{
            this.mMaxYear = null;
            this.mMaxMonth = null;
            this.mMaxDay = null;
        }
        return this;
    }

    @Override
    public IDateChooser setTag(Object tag) {
        this.mTag = tag;
        return this;
    }


    @Override
    public IDateChooser setFlag(int flag) {
        this.flag = flag;
        return this;
    }

    @Override
    public Object getTag() {
        return mTag;
    }

    @Override
    public IDateChooser setCallback(Callback callback) {
        this.mCallback = callback;
        return this;
    }


    /**
     * 设置窗口的属性
     *
     * @param width   窗口宽 例：WindowManager.LayoutParams.MATCH_PARENT
     * @param height  高 例：200
     * @param gravity 位子 例：Gravity.BOTTOM
     */
    public void setAttributes(int width, int height, int gravity) {
        WindowManager.LayoutParams attributes = this.getWindow().getAttributes();
        attributes.width = width;
        attributes.height = height;
        attributes.gravity = gravity;
        this.getWindow().setAttributes(attributes);

    }

    /**
     * 设置动画
     *
     * @param resId R.style.anim_window_popu动 画
     */
    public void setWindowAnimations(@StyleRes int resId) {
        this.getWindow().setWindowAnimations(resId);
    }

    @Override
    public void show() {
        super.show();
        setAttributes(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        setSelectedYear(mYear);
        setSelectedMonth(mMonth);
        setSelectedDay(mDay);
        setSelectedHour(mHour);
        setSelectedMinute(mMinute);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.date_cancel) {
            dismiss();
        } else if (v.getId() == R.id.date_ok) {
            mYear = mNumberPickerYear.getDisplayedValues()[mNumberPickerYear.getValue()];
            mMonth = mNumberPickerMonth.getDisplayedValues()[mNumberPickerMonth.getValue()];
            mDay = mNumberPickerDay.getDisplayedValues()[mNumberPickerDay.getValue()];
            mHour = mNumberPickerHour.getDisplayedValues()[mNumberPickerHour.getValue()];
            mMinute = mNumberPickerMinute.getDisplayedValues()[mNumberPickerMinute.getValue()];
            if (mCallback instanceof Callback2) {
                ((Callback2) mCallback).onChange(mYear, mMonth, mDay, mHour, mMinute);
            } else {
                mCallback.onChange(mYear, mMonth, mDay);
            }


//            Toast.makeText(getContext(),year+"-"+month+"-"+day , Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        int id = picker.getId();
        if (id == R.id.date_numberPicker_year) {
            //年
            String[] years = picker.getDisplayedValues();
            String oldyear = years[oldVal];
            String newyear = years[newVal];
            //当前选择的月为2月
            if (mNumberPickerMonth.getValue() == 1) {
                if (TimeUtils.isLeapYear(oldyear) != TimeUtils.isLeapYear(newyear)) {
                    initDay(newyear, "2");
                }
            }
            initMonth(newyear);
            String newMonth = mNumberPickerMonth.getDisplayedValues()[mNumberPickerMonth.getValue()];
            LogUtils.d(TAG, "onValueChange:newyear=" + newyear + ",newMonth=" + newMonth);
            initDay(newyear, newMonth);

        } else if (id == R.id.date_numberPicker_month) {
            //月
            int v = newVal + 1;
            String newMonth = v >10 ? "" + v : "0" + v;

            String year = mNumberPickerYear.getDisplayedValues()[mNumberPickerYear.getValue()];
            LogUtils.d(TAG, "onValueChange:year=" + year + ",newMonth=" + newMonth);

            initDay(year, newMonth);
        }
    }


}
